package com.zs.controller;

import com.alibaba.fastjson.JSONObject;
import com.zs.bean.User;
import com.zs.service.UserService;
import com.zs.util.Util;
import com.zs.util.XlsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * Created by zhangshuqing on 2017/12/2.
 */


@Controller
public class IndexController {

    private Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String hello(Model model) {
        return "index";
    }


    /**
     * 上传文件
     *
     * @param loadFile
     * @return
     */
    @RequestMapping(value = "load", method = RequestMethod.POST)
    public String loadFile(@RequestParam(value = "loadFile", required = true) MultipartFile loadFile,Model model) throws IOException {
        String fileName = loadFile.getOriginalFilename();
        String code= Util.getUUID();
        List<User> userList = XlsUtil.readUserList(loadFile.getInputStream(), fileName,code);
        userService.saveUser(userList);
        model.addAttribute("userList",userList);
        model.addAttribute("code",code);
        return "success";
    }


    @RequestMapping(value = "query", method = RequestMethod.GET)
    @ResponseBody
    public List<User> findAllUser(@RequestParam(value = "code" ,required = true) String code ){
        List<User> result=userService.findUserByCode(code.toLowerCase());
        logger.info("CODE:{}，联系人条目：{}",code,result.size());
        return result;
    }

}
